package com.zrrd.jt_admin.manager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.jt_admin.common.vo.RoleVo;
import com.zrrd.jt_admin.common.bo.RoleRuleBo;
import com.zrrd.jt_admin.common.entity.Role;
import com.zrrd.jt_admin.common.entity.RoleRule;
import com.zrrd.jt_admin.common.page.RolePageVo;
import com.zrrd.jt_admin.manager.mapper.RoleMapper;
import com.zrrd.jt_admin.manager.service.RoleRuleService;
import com.zrrd.jt_admin.manager.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wanjl
 * @since 2024-06-25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleRuleService rrService;


    private List<RoleRuleBo> getRulesByRoleId(Integer roleId) {
        List<RoleRule> rrList = rrService.lambdaQuery().eq(RoleRule::getRoleId, roleId).list();

        List<RoleRuleBo> list = rrList.stream().map(roleRule -> {
            RoleRuleBo roleRuleBo = new RoleRuleBo();
            roleRuleBo.setId(roleRule.getRuleId());
            roleRuleBo.setPivot(roleRule);
            return roleRuleBo;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public RolePageVo findByPage(Integer page, Integer limit) {
        //创建要返回的对象
        RolePageVo rolePageVo = new RolePageVo();
        //开始分页
        PageHelper.startPage(page, limit);
        //查询角色信息列表(格式和数据库一致的)  PO  POJO Entity  DO(Data Object)
        List<Role> roleList = list();
        //将集合放入PageInfo分页信息
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);

        //根据业务需要，把roleList集合中的每个role元素的属性值，要复制到roleBo对象中，并形成一个新的集合roleBoList
        List<RoleVo> roleVoList = pageInfo.getList().stream().map(role -> {
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(role, roleVo);

            List<RoleRuleBo> roleRuleBoList = getRulesByRoleId(role.getId());
            roleVo.setRules(roleRuleBoList);

            return roleVo;
        }).collect(Collectors.toList());

        rolePageVo.setList(roleVoList);
        rolePageVo.setTotalCount(pageInfo.getTotal());

        return rolePageVo;
    }
}
